import merge from 'lodash/merge'
import pick from 'lodash/pick'
import uniqueId from 'lodash/uniqueId'
import upperFirst from 'lodash/upperFirst'

const toQueryString = obj =>
  Object.keys(obj)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
    .join('&')

const addListener = (target, eventName, handler) => {
  if (typeof handler === 'function') target.on(eventName, handler)
}

const getBox = (x, y, width, height) => {
  const x1 = x + width < x ? x + width : x
  const x2 = x + width > x ? x + width : x
  const y1 = y + height < y ? y + height : y
  const y2 = y + height > y ? y + height : y
  return {
    x1,
    x2,
    y1,
    y2
  }
}

// 生成随机坐标
const getRandomPosition = (that, jsonData, pageWidth, pageHeight, forWidth, forHeight, state) => {
  if (!pageWidth || !pageHeight) return
  const positions = []
  // 节点间最小距离
  const minDistance = 20
  // const nodes = jsonData.nodes
  const nodes = jsonData
  let count = 0
  // 请注意,如果pageWidth和pageHeight有小数点,可能会导致死循环
  while (positions.length < nodes.length) {
    count++
    if (count > 999) {
      console.log('死循环了')
      break
    }
    const x = Math.random() * (pageWidth - minDistance * 2) - 60
    const y = Math.random() * (pageHeight - minDistance * 2) - 60
    x = x + forWidth
    if (state) {
      y = y + forHeight
    }


    // 检查新的坐标是否与已存在的节点坐标重叠
    const isOverlap = positions.every((pos, index) => {
      const distance = Math.sqrt(
        Math.pow(pos[0] - x, 2) + Math.pow(pos[1] - y, 2)
      )
      return distance > minDistance + positions[index][2]
    })
    if (isOverlap) {
      positions.push([x, y, 60])
    }
  }
  for (var i = 0; i < positions.length; i++) {
    that.$set(nodes[i], 'x', positions[i][0])
    that.$set(nodes[i], 'y', positions[i][1])
  }
  // that.$set(jsonData, 'nodes', nodes)
  return jsonData
}

export {
  merge,
  pick,
  toQueryString,
  uniqueId,
  upperFirst,
  addListener,
  getBox,
  getRandomPosition
}
